<template>
  <HeaderComp></HeaderComp>
  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <van-field
        v-model="loginname"
        name="loginname"
        label="用户名"
        placeholder="用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="password"
        type="password"
        name="password"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
    </van-cell-group>
    <div style="margin: 16px">
      <van-button round block type="primary" native-type="submit">
        立即登录
      </van-button>
    </div>
  </van-form>
  <!-- 注册区域 -->
  <van-cell-group title="去注册">
    <van-cell title="快速注册" is-link to="/reg" />
  </van-cell-group>

  <van-cell-group title="忘记密码?">
    <van-cell title="找回密码" is-link to="/findpass" />
  </van-cell-group>
</template>

<script setup lang="ts">
import { ref } from "vue";
import type { Ref } from "vue";
import { userLogin } from "../api/api";
import { useUserInfoStore } from "@/stores/userInfo";
import { useRouter } from "vue-router";
import { Toast } from "vant";
import { showSuccessToast, showFailToast } from "vant";

interface IUserFrom {
  loginname: string;
  password: string;
}
interface IUserLoginAPI {
  code: "200" | "10011" | "10010";
  data: {
    token: string;
    userid: string;
  };
  message: string;
}

const loginname: Ref<string> = ref("");
const password: Ref<string> = ref("");
const store = useUserInfoStore();
const router = useRouter();

const onSubmit = async (values: IUserFrom) => {
  const res = (await userLogin(values)) as unknown as IUserLoginAPI;
  if (res.code === "200") {
    showSuccessToast(res.message);
    // 1.将用户信息存入store中，取出来做验证
    // store.state.变量名 = 变量
    store.userData = res.data;
    // 2.将用户信息存入localstorage，为了持久化存储
    localStorage.setItem("userData", JSON.stringify(res.data));
    router.push("/");
  } else {
    showFailToast(res.message);
  }
};
</script>

<style lang="scss" scoped>
.van-button--primary {
  background: yellow;
  color: black;
  border: none;
}
.van-form {
  .van-cell-group--inset {
    margin-bottom: 100px;
    margin-top: 50px;
    .van-cell:first-child {
      margin-top: 30px;
      margin-bottom: 30px;
    }
  }
}
</style>
